package org.github.p2w.util;

import org.github.p2w.constant.Constant;
import org.github.p2w.entity.Config;
import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Map;

/**
 * yaml工具类
 *
 * @author xiayongchao
 * @date 2022/10/27
 */
public class YamlUtil {

    public static Config getConfig() {
        InputStream inputStream = YamlUtil.class.getClassLoader().getResourceAsStream(Constant.CONFIG_PATH);
        Map<String, String> yamlMap = new Yaml().load(inputStream);
        if (yamlMap == null || yamlMap.isEmpty()) {
            throw new RuntimeException("没有找到配置文件");
        }
        Config config = new Config();
        Field[] fields = Config.class.getDeclaredFields();
        try {
            for (Field field : fields) {
                Object value = yamlMap.get(field.getName());
                field.setAccessible(true);
                field.set(config, value);
            }
        } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return config;
    }
}
